<template>
	<view>
		<view>
			<table-title content="会议室预约办理表详情"></table-title>
			<view class="record-id">单号：{{processNo}}</view>
			<view class="in-center">
				<small-title content="基本资料"></small-title>
				<view class="state-bar">
					<view class="state-msg">{{state}}</view>
				</view>
			</view>
			<view class="item-table">
				<view-item name="楼盘" :value="userMsg.userBuilding"></view-item>
				<view-item name="楼层" :value="userMsg.userFloor" :isLast="true"></view-item>
			</view>
			<small-title :content="'房间号：' + roomArg.title"></small-title>
			<small-title :content="'预约日期：' + roomArg.date"></small-title>
			<small-title :content="'预约时段：' + roomArg.time"></small-title>
			<small-title :content="'使用免费配额：' + roomArg.useFreeTime + '小时'"></small-title>
			<small-title :content="'套餐选择：' + roomArg.serviceName"></small-title>
			<small-title :content="'费用合计：' + roomArg.price + '元'"></small-title>
			<con-advance-pay-small-title v-if="state==='待申请' && roomArg.price > 0" content="支付方式"></con-advance-pay-small-title>
			<view v-if="state==='待申请' && roomArg.price > 0" style="display: flex;justify-content: center;">
				<radio-group class="payway-style" @change="changePayway">
					<label style="display: flex;">
						<radio :checked="payway[0]" :disabled="state!=='待申请'" class="first-radio" color="#FF0000" value="alipay"></radio>
						<view class="payway-choice">
							<image src="../../../static/alipay-logo.svg" class="payway-logo"></image>
							<view style="font-size: 30rpx;">支付宝支付</view>
						</view>
					</label>
					<label style="display: flex;">
						<radio :checked="payway[1]" :disabled="state!=='待申请'" class="second-radio" color="#FF0000" value="wechat"></radio>
						<view class="payway-choice">
							<image src="../../../static/wechat-logo.svg" class="payway-logo"></image>
							<view style="font-size: 30rpx;">微信支付</view>
						</view>
					</label>
				</radio-group>
			</view>
			<small-title content="处理进度"></small-title>
			<proccess-bar v-if="processFlag" ref="proccessBar" :proccessList="proccessListDefult"></proccess-bar>
			<view v-if="state==='待使用完毕'" class="mix-button">
				<view class="left-part">
					<button v-if="isConfirmable" :class="isConfirmable ? 'left-button' : 'left-button-disabled'" @click="open(0)">使用完毕</button>
					<button v-if="!isConfirmable" :class="isConfirmable ? 'left-button' : 'left-button-disabled'" @click="modOrder">使用完毕</button>
				</view>
				<view class="right-part">
					<button class="right-button" @click="open(1)">取消预约</button>
				</view>
			</view>
			<view v-if="state==='待申请'" class="mix-button">
				<view class="left-part">
					<button class="left-button" @click="isFree" >立即申请</button>
				</view>
				<view class="right-part">
					<button class="right-button" @click="back">返回</button>
				</view>
			</view>
			<view style="height: 200rpx;"></view>
		</view>
		<uni-popup ref="popup" type="dialog">
			<uni-popup-dialog mode="base" :content="endType==0?'是否确认使用完毕？':'是否确认取消预约？'" :duration="2000" :before-close="true" @close="close" @confirm="confirm"></uni-popup-dialog>
		</uni-popup>
	</view>
</template>		

<script>
	import {
		ONLINE_SERVER_ADDRESS_BASE
	} from "../../..//util/network.js"
	import {
		processHistoryList
	} from "../../../util/common.js"
	export default{
		data() {
			return {
				processFlag:false,
				status:-1,
				token:'',
				recordId: '',                                                         //单号
				processNo:'待分配',
				state: '已受理',																	   //状态
				roomArg: {
					'id': 0,
					'title': "",
					'date': "",
					'time': "",
					'serviceId': 0,
					'serviceName': "",
					'price': 0,
					'useFreeTime':0,
				},
				userMsg:{'userName':'','userPhone':'','userCompany':'','userBuilding':'',
					'userFloor':'','userRoom':''},
				spend:0,                                                                           //会议室总费用
				payway: [true, false],                                                            //支付方式
				proccessList:[
					{'type':'firstCanvas','commentMsg':'发起申请','time':'2021-01-01 01:01:11'},
					{'type':'middleCanvas','commentMsg':'受理','time':'2020-02-02 02:02:22'},
					{'type':'lastCanvas','commentMsg':'办结','time':'2020-03-03 03:33:33'}
				],                                                                                 //处理进度
				proccessListDefult:[],
				isConfirmable:false,
				endType:0,
			}
		},
		methods: {
			open(type) {
				this.endType = type
				this.$refs.popup.open()
			},
			/**
			 * 点击取消按钮触发
			 * @param {Object} done
			 */
			close() {
				// TODO 做一些其他的事情，before-close 为true的情况下，手动执行 close 才会关闭对话框
				// ...
				this.$refs.popup.close()
			},
			/**
			 * 点击确认按钮触发
			 * @param {Object} done
			 * @param {Object} value
			 */
			confirm(value) {
				// 输入框的值
				console.log(value)
				// TODO 做一些其他的事情，手动执行 close 才会关闭对话框
				// ...
				if(this.endType == 0){
					this.modOrder()
				}else{
					this.cancelOrder()
				}
				this.$refs.popup.close()
			},
			
			/*
			功能：在线支付通用方法
			参数：无
			*/
		    onlinePay(){
		    	let orderInfo = "等后端接口"
				let orderNo = ""
		    	let paywaySingle = ''
				let _this = this
		    	if(this.payway[0]){
		    		paywaySingle = 'alipay'
		    	}else{
		    		paywaySingle = 'wxpay'
		    	}
				let startTime = this.roomArg.date + ' ' + this.roomArg.time.split('~')[0]
				let endTime = this.roomArg.date + ' ' + this.roomArg.time.split('~')[1]
				let extraInfo = {
						comboId:this.roomArg.serviceId,
						meetingRoomId:this.roomArg.id,
						startTime:startTime,
						endTime:endTime,
						useFreeTime:this.roomArg.useFreeTime,
						price:this.roomArg.price,
						useType:1,
						userType:0,
						commentMsg: '发起申请'                       //操作信息
					}
		    	uni.request({
		    		url:`${ONLINE_SERVER_ADDRESS_BASE}/pay/pay`,
		    		header: {
		    			'Authorization': this.token,
		    		},
		    		data: {
		    			orderName: "会议室预约",
		    			payPlatform: paywaySingle,                        //待写入工单内容
						orderType:1,
						extraInfo:JSON.stringify(extraInfo),
						amount: Number(this.roomArg.price),
						recordId:-1,
		    		},
		    		method:'POST',
		    		success: function (res) {
		    			console.log("提交成功",res.data);
		    			if(res.data.code == 200){
		    				if(paywaySingle == 'wxpay'){
		    					orderInfo = res.data.data.wxPayOrderInfo
								orderNo = res.data.data.orderNo
		    				}else{
		    					orderInfo = res.data.data.aliPayOrderInfo
								orderNo = res.data.data.orderNo
		    				}
		    				uni.requestPayment({  
		    					provider: paywaySingle,  
		    					orderInfo: orderInfo,  
		    					success: (e) => {  
		    						console.log(e);  
									uni.navigateBack({
										delta: 2
									});
									// _this.addOrder(orderNo) //addOrder('2021121210515022154')
		    					},  
		    					fail: (e) => {  
									console.log(e);
		    					}  
		    				});
		    			}
		    		}
		    	})
		    },
			
			/*
			功能：选择支付方式
			参数：无
			*/
			changePayway(e){
				console.log('-change事件:', e.detail.value)
				if(e.detail.value == "alipay"){
					this.payway=[true,false];
				}else{
					this.payway=[false,true];
				}
			},
			
			/*
			功能：工单详细页处理通用函数
			参数：
			option：操作类型（先定成 创建、写入、查询）
			*/
			addOrder(orderNo){
				console.log("[info]","工单已创建，工单号为：待分配")
				let startTime = this.roomArg.date + ' ' + this.roomArg.time.split('~')[0]
				let endTime = this.roomArg.date + ' ' + this.roomArg.time.split('~')[1]
				let order = 1
				if(orderNo == '免费'){
					order = 0
				}
				console.log('免费时长',this.roomArg.useFreeTime)
				uni.request({
					url:`${ONLINE_SERVER_ADDRESS_BASE}/meeting-room-reserve/add`,
					header: {
						'Authorization': this.token,
					},
					data: {
						orderNo:orderNo,
						comboId:this.roomArg.serviceId,
						meetingRoomId:this.roomArg.id,
						startTime:startTime,
						endTime:endTime,
						useFreeTime:this.roomArg.useFreeTime,
						price:this.roomArg.price,
						useType:1,
						userType:0,
						commentMsg: '发起申请'                       //操作信息
					},
					method:'POST',
					success: function (res) {
						console.log("会议室预约add", res)
						if(res.data.code == 200 || res.data.code == 4000){
						    uni.navigateBack({
								delta: 2
						    });
						}else{
							uni.showModal({
								content:'服务器异常，请联系工作人员',
								showCancel:false
							})
						}
					},
					fail: (e) => {
						uni.showModal({
							content:"服务器异常，请联系工作人员",
							showCancel:false
						})
					}  
					
				})
			},
			isFree(){
				console.log("[info]","工单已创建，工单号为：待分配")
				let _this = this
				let startTime = this.roomArg.date + ' ' + this.roomArg.time.split('~')[0]
				let endTime = this.roomArg.date + ' ' + this.roomArg.time.split('~')[1]
				uni.request({
					url:`${ONLINE_SERVER_ADDRESS_BASE}/meeting-room-reserve/is-free/` + this.roomArg.id,
					header: {
						'Authorization': this.token,
					},
					data: {
						startTime:startTime,
						endTime:endTime,
					},
					method:'POST',
					success: function (res) {
						console.log("会议室预约free", res)
						if(res.data.code == 200){
							if(res.data.data == true){
								if(_this.roomArg.price == 0){
									_this.addOrder('免费')
								}else{
									_this.onlinePay()
								}
							}else{
								uni.showModal({
									content:'该时段已被其它用户下单预约，请重新选择预约时段，或稍后30秒再试',
									showCancel:false
								})
							}
						}else{
							uni.showModal({
								content:'查询预约状态超时，请检查网络状况',
								showCancel:false
							})
						}
					}
				})
			},
		   modOrder(){
			if(!this.isConfirmable){
				uni.showModal({
					content:'当前会议室未使用完毕',
					showCancel:false
				})
				return -1
			}
		   	console.log("[info]","会议室使用完毕办结：" + this.recordId)
		   	uni.request({
		   		url:`${ONLINE_SERVER_ADDRESS_BASE}/meeting-room-reserve/finish/` + this.recordId,
		   		header: {
		   			'Authorization': this.token,
		   		},
		   		data: {
		   			commentMsg: '用户已确认会议室使用完毕'                       //操作信息
		   		},
		   		method:'POST',
		   		success: function (res) {
		   			console.log("会议室使用完毕成功",res);
					if(res.data.code == 200){
						uni.navigateBack()
					}
		   		},
		   		fail: (res) => {
		   			console.log("会议室使用完毕调用失败")
		   		}
		   	})
		   },
		   checkCancel(endTime){
			   let dateTime = new Date(endTime.replace(/-/g, "/"));  // replace方法将 - 转为 /
			   let dateNow = new Date();  // 获取当前时间
			   let timeDiff =(dateTime.getTime() - dateNow.getTime())/1000;  // 时间差的毫秒数
			   if(timeDiff < 3600){
				   return -1
			   }else{
				   return 0
			   }
		   },
		   cancelOrder(){
			   if(this.checkCancel(this.roomArg.time.split('~')[1]) == -1){
				   uni.showModal({
				   	content:'预约开始时间一小时内无法申请取消',
				   	showCancel:false
				   })
				   return -1
			   }
		   	console.log("[info]","申请取消会议室预约办结：" + this.recordId)
		   	uni.request({
		   		url:`${ONLINE_SERVER_ADDRESS_BASE}/meeting-room-reserve/cancel/` + this.recordId,
		   		header: {
		   			'Authorization': this.token,
		   		},
		   		data: {
		   			commentMsg: '用户申请取消会议室预约'                       //操作信息
		   		},
		   		method:'POST',
		   		success: function (res) {
		   			console.log("用户申请取消成功",res);
					if(res.data.code == 200){
						uni.navigateBack()
					}else{
						uni.showModal({
							content:'预约开始时间一小时内无法申请取消',
							showCancel:false
						})
					}
		   		},
		   		fail: (res) => {
		   			console.log("用户申请取消调用失败")
		   		}
		   	})
		   },
		   getOrder(){
			   let _this = this
				console.log("[info]","会议室预约申请查询成功，工单号为：" + this.recordId)
				uni.request({
					url:`${ONLINE_SERVER_ADDRESS_BASE}/meeting-room-reserve/show/` + this.recordId,
					header: {
						'Authorization': this.token,
					},
					method:'GET',
					success: function (res) {
						_this.status = parseInt(res.data.data.status)
						switch(_this.status) {
						     case 0:
						        _this.state = "待管家确认"
						        break;
						     case 1:
						        _this.state = "待使用完毕"
						        break;
							 case 2:
						        _this.state = "使用完毕"
							    break;
							 case 3:
						        _this.state = "待审批取消"
							    break;
							 case 4:
						        _this.state = "待财务退款"
							    break;
						     case 5:
						        _this.state = "预定已取消"
						        break;
						     case 6:
						        _this.state = "预定已驳回"
						        break;
						     default:
							    _this.status = -1
						        _this.state = "待申请"
						} 
						console.log("查询成功详细工单",res.data);
						_this.processNo = res.data.data.processNo
						_this.roomArg.id = res.data.data.meetingRoomId                     //会议室ID
						_this.roomArg.serviceId = res.data.data.comboId                     //会议室ID
						_this.roomArg.useFreeTime = (res.data.data.useFreeTime == null) ? 0 : res.data.data.useFreeTime                     //会议室ID
						_this.getRoomAndComboInfo(_this.roomArg.id,_this.roomArg.serviceId)
						_this.roomArg.date = res.data.data.startTime.split('T')[0]               //预约日期
						_this.roomArg.time = res.data.data.startTime.split('T')[1] + '~' + res.data.data.endTime.split('T')[1]                      //预约时段
						_this.isConfirmable = false
						let curDate = Date.parse(new Date())
						let timeSum = curDate - Date.parse(res.data.data.startTime.replace('T','').replace(/-/g, '/'))
						if(timeSum > 1000){
							_this.isConfirmable = true
						}
						_this.roomArg.price = res.data.data.price                //总费用
						_this.proccessListDefult = processHistoryList(res.data.data.processDetail)
						_this.processFlag = true		
					}
				})
		   },
		   getRoomAndComboInfo(roomId,comboId){
			   let _this = this
			   uni.request({
			   	url:`${ONLINE_SERVER_ADDRESS_BASE}/meeting-room/show/` + roomId,
			   	header: {
			   		'Authorization': this.token,
			   	},
			   	method:'GET',
			   	success: function (res) {
			   		if(res.data.code == 200){
			   			_this.roomArg.title = res.data.data.houseNo	
			   		}
			   	},
			   	fail: (res) => {
			   		console.log("查询会议室失败")
			   	}
			   })
			   if(comboId >= 0){
				   uni.request({
				   	url:`${ONLINE_SERVER_ADDRESS_BASE}/meeting-room-combo/show/` + comboId,
				   	header: {
				   		'Authorization': this.token,
				   	},
				   	method:'GET',
				   	success: function (res) {
				   		if(res.data.code == 200){
				   			_this.roomArg.serviceName = res.data.data.name	
				   		}
				   	},
				   	fail: (res) => {
				   		console.log("查询套餐失败")
				   	}
				   })
			   }else{
				   _this.roomArg.serviceName = "未选择套餐"
			   }
		   },
		   back(){
			   uni.navigateBack({
			   	delta: 1
			   });
		   },
		},
		onLoad(option) {
			let userInfo = uni.getStorageSync('userinfo')
			if(userInfo != null){
				this.userMsg.userBuilding = userInfo.title
				this.userMsg.userFloor = userInfo.floor
				this.recordId = option.id
				this.state = option.state
				this.token = uni.getStorageSync('token')
				try{
					const item = JSON.parse(decodeURIComponent(option.roomArg))
					this.roomArg = item
				}catch(e){
					//TODO handle the exception
				}
			}else{
				uni.navigateTo('../../login/login')
			}
		},
		onReady() {
			if(this.state != '待申请'){
				this.getOrder()
			}else{

			}
		}
	}
</script>

<style>
	page{
		background-color: #F1F1F1
	}
	.record-id{
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 30rpx;
	}
	.state-bar{
		display: flex;
		align-items: center;
		color: #FFFFFF;
		background-color: #DD524D;
		width: 260rpx;
		justify-content: center;
		margin-left: auto;
		margin-right: 50rpx;
		font-size: 30rpx;
		border-radius: 50rpx;
		height: 50rpx;
	}
	.state-msg{
		display: flex;
		align-items: center;
		justify-content: center;
	}
	.item-table{
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}
	.mix-button{
		display: flex;
		align-items: center;
		justify-content: center;
	}
	.left-part{
		float: right;
	}
	.right-part{
		float: left;
	}
	.left-button{
		background-color: #FF0000;
		border-radius: 50rpx 0 0 50rpx;
		color: #FFFFFF;
		width: 300rpx;
		font-size: 30rpx;
	}
	.left-button-disabled{
		background-color: #FF0000;
		border-radius: 50rpx 0 0 50rpx;
		color: #a6a6a6;
		width: 300rpx;
		font-size: 30rpx;
	}
	.right-button{
		background-color: #0000FF;
		border-radius: 0 50rpx 50rpx 0;
		color: #FFFFFF;
		width: 300rpx;
		font-size: 30rpx;
	}
	.in-center{
		display: flex;
		flex-direction: row;
		align-items: center;
	}
	.add-button {
		border-width: 0px;
		align-items: center;
		justify-content: center;
		margin: 30rpx 0 40rpx 250rpx;
		height: 50rpx;
		width: 250rpx;
		display: flex;
		color: #22B242;
	}
	.payway-style {
		display: flex;
		flex-direction: column;
		width: 665rpx;
		margin-left: 18rpx;
	}
	.first-radio {
		height: 100rpx;
		display: flex;
		align-items: center;
		background-color: #FFFFFF;
		padding-left: 25rpx;
		border: solid 0rpx #C8C7CC;
		border-bottom: none;
		border-right: none;
	}
	.second-radio {
		height: 100rpx;
		display: flex;
		align-items: center;
		background-color: #FFFFFF;
		padding-left: 25rpx;
		border: solid 0rpx #C8C7CC;
		border-right: none;
		width: 50rpx;
	}
	.payway-choice {
		display: flex;
		align-items: center;
		background-color: #FFFFFF;
		border: solid 0rpx #C8C7CC;
		width: 600rpx;
		border-left: none;
	}
	.payway-logo {
		width: 50rpx;
		height: 50rpx;
		margin: 0 25rpx 0 25rpx;
	}
</style>
